from django import forms
from django.core.exceptions import ValidationError
import pdb, json
from user.models import VSession, FileStore, Company, WarZone
from software.models import SoftwareType, Software, SoftwareVersion
from storehouse.models import Storehouse
from order.models import SoftwareOrder


def token_check(value):
    # 验证token必须存在
    sessionList = VSession.objects.filter(token=value)
    if not sessionList.exists():
        errMsg = 'token Error'
        raise ValidationError(errMsg)
    else:
        session = sessionList[0]


def order_check(value):
    # 验证token必须存在
    is_num_by_except(value)
    order = SoftwareOrder.objects.filter(pk=value)
    if not order.exists():
        errMsg = 'order Error'
        raise ValidationError(errMsg)
    else:
        order = order[0]


def maxItem_check(value):
    if value < 1:
        errMsg = 'maxItem Error'
        raise ValidationError(errMsg)


def page_check(value):
    if value < 1:
        errMsg = 'page Error'
        raise ValidationError(errMsg)


def company_check(value):
    # 验证token必须存在
    is_num_by_except(value)
    company = Company.objects.filter(pk=value)
    if not company.exists():
        errMsg = 'company Error'
        raise ValidationError(errMsg)
    else:
        session = company[0]


def warZone_check(value):
    # 验证token必须存在
    is_num_by_except(value)
    warZone = WarZone.objects.filter(pk=value)
    if not warZone.exists():
        errMsg = 'warZone Error'
        raise ValidationError(errMsg)
    else:
        session = warZone[0]


def is_num_by_except(num):
    try:
        int(num)
        return True
    except ValueError:
        errMsg = 'value not int'
        raise ValidationError(errMsg)


class OrderListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    softwareGroup = forms.CharField(max_length=20)

    def clean(self):
        cleaned_data = super(OrderListForm, self).clean()
        softwareGroup = cleaned_data.get('softwareGroup')
        token = cleaned_data.get('token')
        # softwareGroup = self.cleaned_data['softwareGroup']
        # token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType == '1':
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
                elif session.user.userType == '2':
                    if softwareGroup != '' and (softwareGroup not in ['0', '1', '2']):
                        errMsg = 'softwareGroup Error'
                        raise ValidationError(errMsg)
                elif session.user.userType == '3':
                    if softwareGroup != '' and (softwareGroup not in ['0', '1', '2']):
                        errMsg = 'softwareGroup Error'
                        raise ValidationError(errMsg)
                else:
                    pass
            else:
                errMsg = 'user Error'
                raise ValidationError(errMsg)
        return self.cleaned_data


class OrderDetailForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    orderId = forms.IntegerField(validators=[order_check])


class OrderDealForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    orderId = forms.IntegerField(validators=[order_check])
    option = forms.CharField(max_length=20)
    status = forms.CharField(max_length=20, required=False)
    result = forms.CharField(max_length=20, required=False)

    def clean(self):
        cleaned_data = super(OrderDealForm, self).clean()
        option = cleaned_data.get('option')
        # option = self.cleaned_data['option']
        if option in ['0', '1', '2', '3']:
            if option == '0':
                result = cleaned_data.get('result')
                # result = self.cleaned_data['result']
                if result == '' or (result not in ['0', '1']):
                    errMsg = 'option Error'
                    raise ValidationError(errMsg)
            elif option == '1':
                status = cleaned_data.get('status')
                # status = self.cleaned_data['status']
                if status == '' or (status not in ['0', '1', '2']):
                    errMsg = 'status Error'
                    raise ValidationError(errMsg)
            else:
                pass
        else:
            errMsg = 'option Error'
            raise ValidationError(errMsg)
        return self.cleaned_data


class OrderSearchForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    warZoneId = forms.CharField(max_length=20, required=False, validators=[warZone_check])
    companyId = forms.CharField(max_length=20, required=False, validators=[company_check])
    softwareName = forms.CharField(max_length=20, required=False)
    softwareGroup = forms.CharField(max_length=20, required=False)

    def clean(self):
        cleaned_data = super(OrderSearchForm, self).clean()
        token = cleaned_data.get('token')
        # token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType not in ['2']:
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
        return self.cleaned_data


class GroupOrderListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    softwareGroup = forms.CharField(max_length=20)
